/**
 * Created by Boyz.X on 2015/9/25.
 */
appModule.controller('OrgCtr', function ($scope, $state, CommonUtils, $http, $stateParams, CustomersService) {
  //var webserver = 'http://192.168.168.245:8080/eos-default/';
  $scope.title = "部门列表";
  var action = eval('(' + $stateParams.action + ')');
  var tempShareDepartments = [];
  //var shareDep;

  $scope.$on('$ionicView.beforeEnter', function () {
    $scope.currentCustomer = CustomersService.getCurrentCustomer();
    if ($scope.currentCustomer.departments) {
      tempShareDepartments = $scope.currentCustomer.departments;
    }
  });
  ///*  $rootScope.currentCustomer.shareUser*/
  //$http.get("json/shareorg.json")
  //  .success(function (data1) {
  //    shareDep = data1.data;
  //  });


  CustomersService.queryAllOrg(function (data) {
    $scope.data = data.OrgName;
  });
  //$http.post(webserver + 'com.chinasie.s2c.users.users.queryAllOrg.biz.ext', {
  //  userId: "222222"
  //}).success(function (data) {
  //  $scope.data = data.OrgName;
  //});

  $scope.back = function () {
    $state.go('customer-edit');
  };

  $scope.checked = function (org) {
    for (var i = 0, n = tempShareDepartments.length; i < n; i++) {
      if (tempShareDepartments[i].depid == org.orgid) {
        return true;
      }
    }
    return false;
  };
  $scope.changStatue = function (org, statue) {
    var tmp = {orgname: org.orgname, cid: $scope.currentCustomer.id, depid: org.orgid};
    if (statue) {
      tempShareDepartments.push(tmp);
    } else {
      var index = -1;
      for (var i = 0, n = tempShareDepartments.length; i < n; i++) {
        if (tempShareDepartments[i].depid == tmp.depid) {
          index = i;
          break;
        }
      }
      if (index > -1) {
        tempShareDepartments.splice(index, 1);
      }
    }
  };
  $scope.updateShareDepartment = function () {
    if ($scope.currentCustomer.id) {
      CustomersService.updateShareDepartments($scope.currentCustomer.cid, tempShareDepartments, function (data) {
        $scope.currentCustomer.users = tempShareDepartments;
        CommonUtils.goBack();
      });
    } else {
      $scope.currentCustomer.departments = tempShareDepartments;
      CommonUtils.goBack();
    }
  };
});
